package com.boyunvision.service.impl;

import com.boyunvision.common.ApiConfig;
import com.boyunvision.entity.iserestful.PushImageForm;
import com.boyunvision.entity.responsresult.BaseJson;
import com.boyunvision.entity.responsresult.BaseJsonFactory;
import com.boyunvision.entity.responsresult.DeleteRecForm;
import com.boyunvision.entity.responsresult.DeleteRecWsForm;
import com.boyunvision.entity.responsresult.ImageResultJson;
import com.boyunvision.entity.responsresult.PushFeatureForm;
import com.boyunvision.entity.responsresult.PushImageJson;
import com.boyunvision.entity.responsresult.RetrieveFeatureForm;
import com.boyunvision.entity.responsresult.RetrieveForm;
import com.boyunvision.entity.responsresult.RetrieveImageForm;
import com.boyunvision.entity.responsresult.SelectImageForm;
import com.boyunvision.entity.responsresult.SelectNumForm;
import com.boyunvision.entity.responsresult.SelectNumJson;
import com.boyunvision.entity.responsresult.UpdateRecForm;
import com.boyunvision.entity.responsresult.UpdateRecWsForm;
import com.boyunvision.exception.OperationException;
import com.boyunvision.service.IseService;
import com.boyunvision.util.Base64;
import com.boyunvision.util.UrlUtil;
import com.imgdb.rawTcp.Api;
import com.imgdb.rawTcp.exception.ApiException;
import com.imgdb.rawTcp.model.Feature;
import com.imgdb.rawTcp.model.ImgRecord;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class IseServiceImpl implements IseService {
  private Log log = LogFactory.getLog(getClass());
  
  @Autowired
  private ApiConfig apiConfig;
  
  public BaseJson createDB(String dbName, String fileList) {
    try {
      this.log.info("method=createDB dbName [" + dbName + "],fileList [" + fileList + "]");
      this.apiConfig.getApi().createDB(dbName, fileList);
      return (BaseJson)new PushImageJson(0, null, 1L);
    } catch (IOException e) {
      this.log.error("method=createDB [" + e.getMessage() + "]");
      e.printStackTrace();
    } catch (ApiException e) {
      this.log.error("method=createDB [" + e.getMsg() + "]");
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(e.getRetcode(), e
          .getMsg());
    } 
    return null;
  }
  
  public BaseJson deleteDB(String dbName) {
    try {
      this.log.info("method=deleteDB dbName [" + dbName + "]");
      this.apiConfig.getApi().deleteDB(dbName);
      return (BaseJson)new PushImageJson(0, null, 1L);
    } catch (IOException ie) {
      ie.printStackTrace();
      this.log.error("method=deleteDB [" + ie.getMessage() + "]");
    } catch (ApiException ae) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(ae.getRetcode(), ae
          .getMsg());
    } 
    return null;
  }
  
  public BaseJson pushImage(PushImageForm form) {
    this.log.info("method=pushImage db_uid = [" + form.getDb_uid() + "]");
    BaseJson bj = null;
    byte[] imagedata = null;
    if (form.getPic_url() != null) {
      this.log.info("method=pushImage getPic_url = [" + form.getPic_url() + "]");
      try {
        imagedata = UrlUtil.requestImageUrl(form.getPic_url());
      } catch (MalformedURLException e1) {
        this.log.error("method=pushImage [" + e1.getMessage() + "]");
        return (BaseJson)BaseJsonFactory.buildIseRestfulJson(400, "图像URL非法");
      } catch (IOException e2) {
        this.log.error("method=pushImage Pic_url [" + e2.getMessage() + "]");
        return (BaseJson)BaseJsonFactory.buildIseRestfulJson(412, "内部图像URL请求失败");
      } 
    } else if (form.getBase64_data() != null) {
      try {
        this.log.info("method=pushImage Base64_data");
        imagedata = Base64.decode(form.getBase64_data());
      } catch (Exception e) {
        this.log.error("method=pushImage Base64_data[" + e.getMessage() + "]");
        return (BaseJson)BaseJsonFactory.buildIseRestfulJson(-29, "BAsE64数据解析错误");
      } 
    } else if (form.getImg_stream() != null) {
      try {
        this.log.info("method=pushImage Img_stream");
        imagedata = form.getImg_stream().getBytes();
      } catch (IOException e) {
        this.log.error("method=pushImage Img_stream[" + e.getMessage() + "]");
        return (BaseJson)BaseJsonFactory.buildIseRestfulJson(401, "图像数据获取失败");
      } 
    } else {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(2, "未找到图像参数");
    } 
    if (imagedata == null)
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(73, "图像数据为空");
    try {
      long index = this.apiConfig.getApi().pushImg(form.getDb_uid(), imagedata, form.getWp(), form.getPl());
      this.log.info("method=pushImage success");
      return (BaseJson)new PushImageJson(0, null, index);
    } catch (IOException e1) {
      this.log.error("method=pushImage [" + e1.getMessage() + "]");
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(404, "系统级别错误,请联系系统管理员.");
    } catch (ApiException e2) {
      this.log.error("method=pushImage [" + e2.getMsg() + "]");
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(e2.getRetcode(), e2
          .getMsg());
    } catch (Exception e3) {
      this.log.error("method=pushImage [" + e3.getMessage() + "]");
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(404, "系统级别错误,请联系系统管理员.");
    } 
  }
  
  public BaseJson pushFeature(PushFeatureForm form) {
    this.log.info("method=pushFeature db_uid = [" + form.getDb_uid() + "]");
    byte[] featureData = null;
    if (form.getFeature_stream() != null) {
      try {
        featureData = form.getFeature_stream().getBytes();
      } catch (IOException e) {
        return (BaseJson)BaseJsonFactory.buildIseRestfulJson(401, "图像数据获取失败");
      } 
    } else {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(2, "未找到图像参数");
    } 
    try {
      Feature feature = new Feature(featureData.length, featureData);
      long index = this.apiConfig.getApi().pushImgFeat(form.getDb_uid(), feature, form
          .getWp(), form.getPl());
      return (BaseJson)new PushImageJson(0, null, index);
    } catch (IOException e1) {
      return 
        (BaseJson)BaseJsonFactory.buildIseRestfulJson(404, "系统级别错误请联系系统管理员.");
    } catch (ApiException e2) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(e2.getRetcode(), e2
          .getMsg());
    } catch (Exception e3) {
      e3.printStackTrace();
      return 
        (BaseJson)BaseJsonFactory.buildIseRestfulJson(404, "系统级别错误请联系系统管理员.");
    } 
  }
  
  public BaseJson retrieveImage(RetrieveImageForm form) {
    Api api = this.apiConfig.getApi();
    byte[] imagedata = null;
    try {
      imagedata = getImageData((RetrieveForm)form);
    } catch (OperationException e) {
      return e.getFailMsg();
    } 
    int sel1 = 100;
    int sel2 = 10;
    float smin = 0.0F;
    if (form.getSel1() > 0)
      sel1 = form.getSel1(); 
    if (form.getSel2() > 0)
      sel2 = form.getSel2(); 
    if (sel2 > sel1)
      sel2 = sel1; 
    if (form.getMin_sim() != -1.0F)
      smin = form.getMin_sim(); 
    try {
      ArrayList<ImgRecord> res = null;
      if (null != form.getRuntimeParam() && form.getRuntimeParam().trim().length() > 0) {
        res = api.retrieveImageV2(form.getDb_uid(), imagedata, form
            .getWp(), form.getWs(), form.getRuntimeParam());
      } else {
        res = api.retrieveImage(form.getDb_uid(), imagedata, form
            .getWp(), form.getWs(), sel1, sel2, smin);
      } 
      return (BaseJson)new ImageResultJson(res.size(), res);
    } catch (IOException e1) {
      this.log.error(e1.getMessage());
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(404, "系统级别错误请联系系统管理员.");
    } catch (ApiException e2) {
      this.log.error(e2.getMessage());
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(e2.getRetcode(), e2
          .getMsg());
    } 
  }
  
  public BaseJson retrieveFeature(RetrieveFeatureForm form) {
    Api api = this.apiConfig.getApi();
    byte[] featuredata = null;
    if (form.getFeature_stream() != null) {
      try {
        featuredata = form.getFeature_stream().getBytes();
      } catch (IOException e) {
        return (BaseJson)BaseJsonFactory.buildIseRestfulJson(401, "图像数据获取失败");
      } 
    } else {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(2, "未获取到特征参数");
    } 
    int sel1 = 100;
    int sel2 = 10;
    float smin = 0.0F;
    if (form.getSel1() > 0)
      sel1 = form.getSel1(); 
    if (form.getSel2() > 0)
      sel2 = form.getSel2(); 
    if (sel2 > sel1)
      sel2 = sel1; 
    if (form.getMin_sim() != -1.0F)
      smin = form.getMin_sim(); 
    try {
      Feature feature = new Feature(featuredata.length, featuredata);
      ArrayList<ImgRecord> res = api.retrieveImageFeat(form.getDb_uid(), feature, form
          .getWp(), form.getWs(), sel1, sel2, smin);
      return (BaseJson)new ImageResultJson(res.size(), res);
    } catch (IOException e1) {
      return 
        (BaseJson)BaseJsonFactory.buildIseRestfulJson(404, "系统级别错误，请联系系统管理员.");
    } catch (ApiException e2) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(e2.getRetcode(), e2
          .getMsg());
    } 
  }
  
  public BaseJson selectImage(SelectImageForm form) {
    Api api = this.apiConfig.getApi();
    try {
      ArrayList<ImgRecord> res = api.selectImgRec(form.getDb_uid(), form.getWp(), form.getWs(), form.getMaxrec());
      return (BaseJson)new ImageResultJson(res.size(), res);
    } catch (IOException e1) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(404, "系统级别错误，请联系系统管理员.");
    } catch (ApiException e2) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(e2.getRetcode(), e2
          .getMsg());
    } 
  }
  
  public BaseJson selectNum(SelectNumForm form) {
    Api api = this.apiConfig.getApi();
    try {
      long count = api.selectRecCount(form.getDb_uid(), form.getWs());
      return (BaseJson)new SelectNumJson(0, count);
    } catch (IOException e1) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(404, "系统级别错误，请联系系统管理员.");
    } catch (ApiException e2) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(e2.getRetcode(), e2
          .getMsg());
    } 
  }
  
  public BaseJson delectRec(DeleteRecForm form) {
    Api api = this.apiConfig.getApi();
    try {
      api.deleteImgRec(form.getDb_uid(), form.getIndex());
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(0, null);
    } catch (IOException e1) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(404, "系统级别错误，请联系系统管理员.");
    } catch (ApiException e2) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(e2.getRetcode(), e2
          .getMsg());
    } 
  }
  
  public BaseJson deleteRecWs(DeleteRecWsForm form) {
    Api api = this.apiConfig.getApi();
    try {
      api.deleteImgRecWs(form.getDb_uid(), form.getWs());
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(0, null);
    } catch (IOException e1) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(404, "系统级别错误，请联系系统管理员.");
    } catch (ApiException e2) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(e2.getRetcode(), e2
          .getMsg());
    } 
  }
  
  public BaseJson updateRec(UpdateRecForm form) {
    Api api = this.apiConfig.getApi();
    try {
      api.updateRec(form.getDb_uid(), form.getIndex(), form.getSs());
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(0, null);
    } catch (IOException e1) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(404, "系统级别错误，请联系系统管理员.");
    } catch (ApiException e2) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(e2.getRetcode(), e2
          .getMsg());
    } 
  }
  
  public BaseJson updateRecWs(UpdateRecWsForm form) {
    Api api = this.apiConfig.getApi();
    try {
      api.updateRecWs(form.getDb_uid(), form.getWs(), form.getSs());
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(0, null);
    } catch (IOException e1) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(404, "系统级别错误，请联系系统管理员.");
    } catch (ApiException e2) {
      return (BaseJson)BaseJsonFactory.buildIseRestfulJson(e2.getRetcode(), e2
          .getMsg());
    } 
  }
  
  private byte[] getImageData(RetrieveForm form) throws OperationException {
    byte[] imagedata = null;
    if (form.getPic_url() != null) {
      try {
        imagedata = UrlUtil.requestImageUrl(form.getPic_url());
      } catch (MalformedURLException e1) {
        this.log.error(e1.getMessage());
        throw new OperationException(
            BaseJsonFactory.buildIseRestfulJson(400, "图像URL非法"), e1);
      } catch (IOException e2) {
        this.log.error(e2.getMessage());
        throw new OperationException(
            BaseJsonFactory.buildIseRestfulJson(412, "内部图像URL请求失败"), e2);
      } 
    } else if (form.getBase64_data() != null) {
      try {
        imagedata = Base64.decode(form.getBase64_data());
      } catch (Exception e) {
        this.log.error(e.getMessage());
        throw new OperationException(
            BaseJsonFactory.buildIseRestfulJson(-29, "BAsE64数据解析错误"), e);
      } 
    } else if (form.getImg_stream() != null) {
      try {
        imagedata = form.getImg_stream().getBytes();
      } catch (IOException e) {
        this.log.error(e.getMessage());
        throw new OperationException(
            BaseJsonFactory.buildIseRestfulJson(401, "图像数据获取失败"), e);
      } 
    } else {
      throw new OperationException(
          BaseJsonFactory.buildIseRestfulJson(2, "未找到图像参数"), null);
    } 
    return imagedata;
  }
}
